package net

import (
	"com/study/util"
	"fmt"
	"net"
)

func Net() {
	go NetServer("tcp", "0.0.0.0:38888")
	NetClient("tcp", "0.0.0.0:38888")
}

func NetServer(network string, address string) {
	fmt.Println("开始监听......", address)
	listen, err := net.Listen(network, address)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer listen.Close()
	for {
		fmt.Println("等待链接中......")
		conn, err := listen.Accept()
		if err != nil {
			fmt.Println(err)
			return
		} else {
			fmt.Println(conn.RemoteAddr(), "链接成功！")
			go process(conn)
		}
	}
}

func process(conn net.Conn) {
	defer conn.Close()
	for {
		buf := make([]byte, 1024)
		n, err := conn.Read(buf)
		if err != nil {
			fmt.Println(err)
		}
		fmt.Println(string(buf[:n]))
	}
}

func NetClient(network string, address string) {
	fmt.Println("开始链接......", address)
	conn, err := net.Dial(network, address)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer conn.Close()
	for {
		conn.Write(util.ReadLine())
	}
}
